/**
 * Project: topdt-jbpm
 * Copyright 2013  Top Digital Technology  Co. Ltd.
 * All right reserved.
 */
package com.topdt.jbpm.form;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import DBstep.iDBManager2000;

import com.thx.common.spring.BeanFactory;
import com.thx.common.util.AppContext;
import com.thx.common.util.DateUtil;
import com.thx.common.util.ThreadLocalContext;
import com.thx.common.web.SessionInfo;
import com.thx.common.web.WebConstant;
import com.topdt.jbpm.Constants;
import com.topdt.jbpm.identity.Department;
import com.topdt.jbpm.identity.IdFactory;
import com.topdt.jbpm.identity.IdentityService;
import com.topdt.jbpm.identity.User;
import com.topdt.jbpm.model.Application;
import com.topdt.jbpm.model.Control;
import com.topdt.jbpm.model.Work;
import com.topdt.jbpm.service.ControlService;
import com.topdt.jbpm.utils.ControlUtils;

/**
 * 建立日期 : 2013-5-20 下午3:16:56<br>
 * 作者 : balance<br>
 * 模块 : <br>
 * 描述 : 抽象表单处理,自定义表单和通用表单通用<br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 * 1 <br>
 * 2 <br>
 */
public abstract class AbstractFormHandle implements FormHandle {

	protected Logger logger=LoggerFactory.getLogger(getClass());

	public Document saveForm(String workId,Document doc){
		doc.setDocId(workId);
		return saveDoc(doc);
	}

	abstract protected Document saveDoc(Document doc);

	public FormUI assemble(Map<String, Object> context){
		return null;
	}

	/**
	 *  @Description    : 获取FormUI
	 *  @Method_Name    : getFormUI
	 *  @param app
	 *  @param fieldControl
	 *  @param funControl
	 *  @param doc
	 *  @param context
	 *  @param work
	 *  @return
	 *  @return         : FormUI
	 *  @Creation Date  : 2015年3月10日 下午6:39:58
	 *  @version        : v1.00
	 *  @Author         : calonlan

	 *  @Update Date    : 2015年3月10日 下午6:39:58
	 *  @Update Author  : calonlan
	 */
	public FormUI getFormUI(Application app, Map<String, String> fieldControl, Map<String, String> funControl,
			Document doc, Map<String, Object> context, Work work) {
		//通用变量
		context.put("appId", work.getAppId());
		context.put("workId", work.getWorkId());
		//应用类型
		String appAttr = app.getAppAttr();
		context.put("appAttr", appAttr);
		HttpServletRequest request = ((HttpServletRequest) ThreadLocalContext.get(Constants.CONTEXT_HTTPREQ));
		context.put("path", request.getContextPath());
		String oaappAdd = AppContext.getProperties("oaappAdd");
		context.put("oaappAdd", oaappAdd);//zhangyong 20150107防止客户端不能预览
		String iSignatureServerPath = AppContext.getProperties("iSignatureServerPath");
		context.put("iSignatureServerPath", iSignatureServerPath);//fengjinshou 20160115 签章服务器路径
		String phoneSignatureServerPath = AppContext.getProperties("phoneSignatureServerPath");
		context.put("phoneSignatureServerPath", phoneSignatureServerPath);//fengjinshou 20160315客户端 签章服务器路径
		if(request.getSession().getAttribute(WebConstant.KEY_USER)!=null){//fengjinshou 20160302 当前用户 的id
			String currentUserId = ((SessionInfo)(request.getSession().getAttribute(WebConstant.KEY_USER))).getUserId();
			context.put("currentUserId",currentUserId);
		}
		if(request.getSession().getAttribute("keysn")!=null){//fengjinshou 20160316 签章密钥盘序号
			String keysn = request.getSession().getAttribute("keysn").toString();
			context.put("keysn",keysn);
		}
		//整合流程环节操作权限
		//正常流程
		if(!work.isFreeFlow()) {
			String[][] menus = FormMenuDefin.getMenuItems(appAttr);
			for (String[] item : menus) {
				if (funControl != null && funControl.size() > 0) {
					//fjs20140716 此处加上非空判断
					Object val = funControl.get(item[0]);
					if(val!=null){
						if (ControlUtils.getFunValue(val)) {
							context.put(item[0], "");
						} else {
							context.put(item[0], "none");
						}

					}
				}
			}

		//自由流程
		} else {
			//起草
			boolean flag = false;
			//自由流程已经提交
			if(context.get("isFreeSubmit") != null && (Boolean)context.get("isFreeSubmit")) {
				flag = true;
			}

			if (work.getWorkState().equals(Work.STATE_START)) {
				if(!flag) {
					context.put("save","");
					context.put("complete", "");
					//公文类应用
					if (Application.APPATTR_DOC.equals(appAttr)
							|| Application.APPATTR_CUSTOM_DOC.equals(appAttr)
							|| Application.APPATTR_CUSTOM_DOC_OPINION.equals(appAttr) ) {
						if (context.get("docControl") == null)
							context.put("docControl", "111");
						//发布
						context.put("publish", "");
					}
				}

			//流转
			} else {
				if(!flag) {
					context.put("save","");
					context.put("complete", "");
					context.put("opinion","");
					//context.put("isOpinion","");//客户端意见
					//context.put("delete", "");
					//公文类应用
					if (Application.APPATTR_DOC.equals(appAttr)
							|| Application.APPATTR_CUSTOM_DOC.equals(appAttr)
							|| Application.APPATTR_CUSTOM_DOC_OPINION.equals(appAttr) ) {
						if (context.get("docControl") == null)
							context.put("docControl", "111");
						//发布
						context.put("publish", "");
					}
				}

			}

		}

		// --整合work的信息
		Map<String, String> workMap = new HashMap<String, String>();
		String title = StringUtils.isNotBlank(work.getWorkTitle())?work.getWorkTitle():"";
		//如果是起草环节，表单标题置为"",设置工作的状态"开始"
		if (work.getWorkState().equals(Work.STATE_START)) {
			context.put("workState", Work.STATE_START);
		} else {
			//如果不是起草环节，表单标题为只读
			context.put("workDefaultTitle", "readonly");
		}
		workMap.put("workTitle", title);

		String starter = work.getStarterName();

		starter = starter == null ? "" : starter;
		workMap.put("starterName", starter);

		Date startTime = work.getStartTime();

		String startTimeStr = startTime == null ? "" : DateUtil.format(startTime, "yyyy-MM-dd HH:mm");

		workMap.put("startTime", startTimeStr);

		String actName = work.getCurActivityName();
		actName = actName == null ? "" : actName;
		workMap.put("curActivityName", actName);
		IdentityService idService = IdFactory.getIdentityServiceFactory().getIdentityService();
		Department dep = idService.getMajorDepOfUser(work.getStarter());
        String deptName = dep.getName() == "" || dep.getName() == null ? "" : dep.getName();
		workMap.put("starterDepName", deptName);
		/* wangxufeng add 工作序号 20150116 */
		String seqNum = work.getSeqNum();
		seqNum = seqNum == null ? "" : seqNum;
		workMap.put("seqNum", seqNum);
		workMap.put("workState", work.getWorkState());
		workMap.put("comId", work.getCompanyId());
		/* add over */
		context.put("work", workMap);



		/*
		 * 整合意见
		 * 2015-02-03 wangxufeng add
		 * 查找是否设置了默认意见，若有则将默认意见传到template页面
		 */
		ControlService controlService = (ControlService) BeanFactory.getBean("controlService");
		String activitiName = actName;
		String curUserName = "";
		String defaultOption = "";
		if(actName.contains(":")){
			activitiName = actName.substring(1, actName.indexOf(":"));
			curUserName = actName.substring(actName.indexOf(":")+1, actName.length()-1);
		}

		User user = (User) ThreadLocalContext.get(Constants.USER_KEY);
		String userName = user.getName();
		if(activitiName.contains("-")){//--动态分支的活动名称   zili
			activitiName = activitiName.substring(activitiName.indexOf("-")+1);
		}
		if(curUserName.indexOf(userName) > -1){
			Object[] objs = {app.getAppId(),app.getFlowId(),activitiName,app.getForm().getFormId()};
			Control control = controlService.getControlByObjects(objs);
			if(control != null && StringUtils.isNotBlank(control.getDefaultOption())){
				defaultOption = control.getDefaultOption();
			}
		}
		context.put("defaultOption", defaultOption);

		//整合表单字段权限(读写性)
		context = getFieldAuthorityContext(app, fieldControl, doc,context, work);

		//是否是公文应用
		if (Application.APPATTR_DOC.equals(app.getAppAttr()) || Application.APPATTR_CUSTOM_DOC.equals(app.getAppAttr())
				|| Application.APPATTR_CUSTOM_DOC_OPINION.equals(app.getAppAttr())) {

			String mHTMLPath="";
			iDBManager2000 DbaObj = new iDBManager2000();
			ResultSet resultSet = null;
			if (DbaObj.OpenConnection()) {
				String mSql = "Select * From arc_document Where WorkId='"
						+ work.getWorkId() + "'";
				try {
					resultSet = DbaObj.ExecuteQuery(mSql);
					if (resultSet.next()) {

						mHTMLPath = resultSet.getString("HTMLPath");
					}
					resultSet.close();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					DbaObj.CloseConnection();
				}
			}
			if(!"".equals(mHTMLPath)){
				context.put("docPath", mHTMLPath);
			}
		}

		//之前已经在context中放置了workId，但是不起作用，具体原因不明
		//context.put("workId", work.getWorkId());

		return generateFormUI(app, fieldControl, funControl, doc, context, work);
	}


	/**
	 *  @Description    : 获取表单字段权限(读写性)，自定义表单和通用表单需要做不同的处理
	 *  @Method_Name    : getFieldAuthorityContext
	 *  @param app
	 *  @param fieldControl
	 *  @param doc
	 *  @param context
	 *  @param work
	 *  @return
	 *  @return         : Map<String,Object>
	 *  @Creation Date  : 2015年3月10日 下午6:41:46
	 *  @version        : v1.00
	 *  @Author         : calonlan

	 *  @Update Date    : 2015年3月10日 下午6:41:46
	 *  @Update Author  : calonlan
	 */
	abstract protected Map<String, Object> getFieldAuthorityContext(Application app,
			Map<String, String> fieldControl, Document doc,
			Map<String, Object> context, Work work);


	/**
	 *  @Description    : 生成FormUI，需要客户程序最后实现
	 *  @Method_Name    : generateFormUI
	 *  @param app
	 *  @param fieldControl
	 *  @param funControl
	 *  @param doc
	 *  @param context
	 *  @param work
	 *  @return
	 *  @return         : FormUI
	 *  @Creation Date  : 2015年3月10日 下午6:38:53
	 *  @version        : v1.00
	 *  @Author         : calonlan

	 *  @Update Date    : 2015年3月10日 下午6:38:53
	 *  @Update Author  : calonlan
	 */
	abstract protected FormUI generateFormUI(Application app, Map<String, String> fieldControl,
			Map<String, String> funControl, Document doc, Map<String, Object> context, Work work);
}
